package com.example.calculator;

import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 计算器主活动类
 * 实现基本的四则运算、百分比计算和清除功能
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    // 上下两个显示框
    private EditText resultText1, resultText2;
    // 当前输入的数字字符串
    private String currentNumber = "";
    // 当前的运算符
    private String operator = "";
    // 第一个操作数
    private double number1 = 0;
    // 标记是否需要开始新的数字输入
    private boolean isNewNumber = true;
    // 标记当前数字是否已包含小数点
    private boolean hasDecimalPoint = false;
    // 记录彩蛋状态
    private boolean count = false;
    //小彩蛋是否开启标志
    private boolean tF = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        initViews();
    }

    /**
     * 初始化视图和按钮点击事件
     */
    private void initViews() {
        resultText1 = findViewById(R.id.result_edit_text1);
        resultText2 = findViewById(R.id.result_edit_text2);
        
        // 更新按钮ID数组，添加新功能按钮
        int[] buttonIds = {
            R.id.zero, R.id.one, R.id.two, R.id.three, R.id.four,
            R.id.five, R.id.six, R.id.seven, R.id.eight, R.id.nine,
            R.id.add, R.id.subtraction, R.id.multiplication, R.id.Division,
            R.id.decimalPoint, R.id.result, R.id.clean, R.id.CE, R.id.perCent,
            R.id.transition, R.id.square, R.id.rootOfARoot
        };

        for (int i = 0; i < buttonIds.length; i++) {
            findViewById(buttonIds[i]).setOnClickListener(this);
        }

        findViewById(R.id.eggshell).setOnClickListener(this);
    }

    /**
     * 处理按钮点击事件
     */
    @Override
    public void onClick(View view) {
        try {
            int viewId = view.getId();

            // 先处理彩蛋按钮，因为它是ImageView而不是Button
            if(viewId == R.id.eggshell){
                if (tF){
                    handleEasterEgg();
                }
                return;
            }

            // 其他按钮的处理
            Button button = (Button) view;
            String buttonText = button.getText().toString();

            // 处理清除按钮
            if (viewId == R.id.clean) {
                clearAll();
                return;
            }

            // 处理清除当前输入按钮
            if (viewId == R.id.CE) {
                clearEntry();
                return;
            }

            // 处理新增的功能按钮
            if (viewId == R.id.transition) {
                handleTransition();
                return;
            }

            if (viewId == R.id.square) {
                handleSquare();
                return;
            }

            if (viewId == R.id.rootOfARoot) {
                handleSquareRoot();
                return;
            }

            // 根据按钮类型分发到不同的处理方法
            if (isNumber(buttonText)) {
                handleNumber(buttonText);
            } else if (buttonText.equals(".")) {
                handleDecimalPoint();
            } else if (isOperator(buttonText)) {
                handleOperator(buttonText);
            } else if (buttonText.equals("%")) {
                handlePercent();
            } else if (buttonText.equals("=")) {
                if (resultText1.getText().toString().equals("") && currentNumber.equals("202203038322")){
                    tF = true;
                    Toast.makeText(this, "彩蛋功能已打开，快来点击logo试试吧！", Toast.LENGTH_SHORT).show();
                    resultText1.setText("点击logo变换主题");
                }
                handleEquals();
            }
        } catch (Exception e) {
            handleError("计算错误");
        }
    }

    /**
     * 判断字符串是否为数字
     */
    private boolean isNumber(String str) {
        return str.matches("\\d");
    }

    /**
     * 判断字符串是否为运算符
     */
    private boolean isOperator(String str) {
        return str.matches("[+\\-*/]");
    }

    /**
     * 处理数字输入
     * 优化了连续输入0的情况
     */
    private void handleNumber(String number) {
        if (isNewNumber) {
            // 如果是新数字且输入0，直接显示0
            if (number.equals("0")) {
                currentNumber = "0";
            } else {
                currentNumber = number;
            }
            isNewNumber = false;
        } else {
            // 如果当前只有0，且输入非0数字，替换0
            if (currentNumber.equals("0") && !number.equals("0")) {
                currentNumber = number;
            } 
            // 如果当前不是0，或者输入的是非0数字，追加数字
            else if (!currentNumber.equals("0") || !number.equals("0")) {
                currentNumber += number;
            }
        }
        resultText2.setText(currentNumber);
    }

    /**
     * 处理小数点输入
     */
    private void handleDecimalPoint() {
        if (!hasDecimalPoint) {
            if (isNewNumber) {
                currentNumber = "0.";
            } else {
                currentNumber += ".";
            }
            hasDecimalPoint = true;
            isNewNumber = false;
            resultText2.setText(currentNumber);
        }
    }

    /**
     * 处理运算符输入
     * @param newOperator 新输入的运算符
     */
    private void handleOperator(String newOperator) {
        if (!currentNumber.isEmpty()) {
            // 如果已有运算符，先计算前面的结果
            if (!operator.isEmpty()) {
                calculateResult();
            }
            number1 = Double.parseDouble(currentNumber);
            operator = newOperator;
            resultText1.setText(formatNumber(number1) + " " + operator);
            isNewNumber = true;
            hasDecimalPoint = false;
        }
    }

    /**
     * 处理百分比计算
     */
    private void handlePercent() {
        if (!currentNumber.isEmpty()) {
            double number = Double.parseDouble(currentNumber);
            number = number / 100;
            currentNumber = formatNumber(number);
            resultText2.setText(currentNumber);
        }
    }

    /**
     * 处理正负转换
     */
    private void handleTransition() {
        if (!currentNumber.isEmpty() && !currentNumber.equals("0")) {
            if (currentNumber.charAt(0) == '-') {
                currentNumber = currentNumber.substring(1);
            } else {
                currentNumber = "-" + currentNumber;
            }
            resultText2.setText(currentNumber);
        }
    }

    /**
     * 处理平方计算
     */
    private void handleSquare() {
        if (!currentNumber.isEmpty()) {
            try {
                double number = Double.parseDouble(currentNumber);
                double result = number * number;
                resultText1.setText(formatNumber(number) + "² =");
                currentNumber = formatNumber(result);
                resultText2.setText(currentNumber);
                isNewNumber = true;
            } catch (NumberFormatException e) {
                handleError("无效输入");
            }
        }
    }

    /**
     * 处理开方计算
     */
    private void handleSquareRoot() {
        if (!currentNumber.isEmpty()) {
            try {
                double number = Double.parseDouble(currentNumber);
                if (number < 0) {
                    handleError("负数不能开方");
                    return;
                }
                double result = Math.sqrt(number);
                resultText1.setText("√" + formatNumber(number) + " =");
                currentNumber = formatNumber(result);
                resultText2.setText(currentNumber);
                isNewNumber = true;
            } catch (NumberFormatException e) {
                handleError("无效输入");
            }
        }
    }

    /**
     * 处理等号按钮
     */
    private void handleEquals() {
        if (currentNumber.isEmpty()) {
            return;
        }
        if (operator.isEmpty()) {
            // 如果没有运算符，直接显示当前数字
//            resultText1.setText(currentNumber + " =");
            return;
        }
        calculateResult();
    }

    /**
     * 处理错误情况
     */
    private void handleError(String errorMessage) {
        resultText2.setText(errorMessage);
        currentNumber = "";
        operator = "";
        isNewNumber = true;
        hasDecimalPoint = false;
    }

    /**
     * 清除所有内容
     */
    private void clearAll() {
        currentNumber = "";
        operator = "";
        number1 = 0;
        isNewNumber = true;
        hasDecimalPoint = false;
        resultText1.setText("");
        resultText2.setText("0");
    }

    /**
     * 清除当前输入
     */
    private void clearEntry() {
        currentNumber = "";
        isNewNumber = true;
        hasDecimalPoint = false;
        resultText2.setText("0");
    }

    /**
     * 格式化数字，处理精度问题
     * @param number 需要格式化的数字
     * @return 格式化后的字符串
     */
    private String formatNumber(double number) {
        // 使用BigDecimal处理浮点数精度问题
        BigDecimal bd = new BigDecimal(number);
        // 保留8位小数，四舍五入，去除末尾的0
        bd = bd.setScale(8, RoundingMode.HALF_UP).stripTrailingZeros();
        return bd.toPlainString();
    }

    /**
     * 计算结果
     * 增强了错误处理
     */
    private void calculateResult() {
        if (!currentNumber.isEmpty() && !operator.isEmpty()) {
            try {
                double number2 = Double.parseDouble(currentNumber);
                double result = 0;

                switch (operator) {
                    case "+":
                        result = number1 + number2;
                        break;
                    case "-":
                        result = number1 - number2;
                        break;
                    case "*":
                        result = number1 * number2;
                        break;
                    case "/":
                        if (number2 == 0) {
                            handleError("除数不能为零");
                            return;
                        }
                        result = number1 / number2;
                        break;
                }

                resultText1.setText(formatNumber(number1) + " " + operator + " " + formatNumber(number2) + " =");
                currentNumber = formatNumber(result);
                resultText2.setText(currentNumber);
                operator = "";
                isNewNumber = true;
                hasDecimalPoint = currentNumber.contains(".");
            } catch (NumberFormatException e) {
                handleError("计算错误");
            }
        }
    }

    /**
     * 处理彩蛋按钮点击事件
     */
    private void handleEasterEgg() {
        View rootView = findViewById(android.R.id.content);
        ImageView eggshellView = findViewById(R.id.eggshell);

        if (count){
            // 切换背景颜色
            rootView.setBackgroundColor(getResources().getColor(R.color.blue1));

            //修改数字键背景颜色
            int[] buttonIds = {
                    R.id.zero, R.id.one, R.id.two, R.id.three, R.id.four,
                    R.id.five, R.id.six, R.id.seven, R.id.eight, R.id.nine,
                    R.id.decimalPoint
            };

            for (int id : buttonIds) {
                Button button = findViewById(id);
                if (button != null) {
                    button.setBackgroundResource(R.drawable.button_normal);
                    button.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.blue2)));
                }
            }

            //修改功能键背景颜色
            int[] buttonIds2 = {
                    R.id.add, R.id.subtraction, R.id.multiplication, R.id.Division,
                    R.id.perCent, R.id.transition, R.id.square, R.id.rootOfARoot
            };

            for (int id : buttonIds2) {
                Button button = findViewById(id);
                if (button != null) {
                    button.setBackgroundResource(R.drawable.button_operator);
                    button.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.blue3)));
                }
            }

            //修改特殊键背景颜色
            Button resultButton = findViewById(R.id.result);
            resultButton.setBackgroundResource(R.drawable.button_equals);
            resultButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.blue4)));

            Button cleanButton = findViewById(R.id.clean);
            cleanButton.setBackgroundResource(R.drawable.button_clear);
            cleanButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.blue5)));

            Button ceButton = findViewById(R.id.CE);
            ceButton.setBackgroundResource(R.drawable.button_clear);
            ceButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.blue5)));

            // 切换彩蛋按钮图片
            eggshellView.setImageResource(R.drawable.logo2);
        } else {
            // 切换背景颜色
            rootView.setBackgroundColor(getResources().getColor(R.color.o1));

            //修改数字键背景颜色
            int[] buttonIds = {
                    R.id.zero, R.id.one, R.id.two, R.id.three, R.id.four,
                    R.id.five, R.id.six, R.id.seven, R.id.eight, R.id.nine,
                    R.id.decimalPoint
            };

            for (int id : buttonIds) {
                Button button = findViewById(id);
                if (button != null) {
                    button.setBackgroundResource(R.drawable.button_normal);
                    button.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.o2)));
                }
            }

            //修改功能键背景颜色
            int[] buttonIds2 = {
                    R.id.add, R.id.subtraction, R.id.multiplication, R.id.Division,
                    R.id.perCent, R.id.transition, R.id.square, R.id.rootOfARoot
            };

            for (int id : buttonIds2) {
                Button button = findViewById(id);
                if (button != null) {
                    button.setBackgroundResource(R.drawable.button_operator);
                    button.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.o3)));
                }
            }

            //修改特殊键背景颜色
            Button resultButton = findViewById(R.id.result);
            resultButton.setBackgroundResource(R.drawable.button_equals);
            resultButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.o4)));

            Button cleanButton = findViewById(R.id.clean);
            cleanButton.setBackgroundResource(R.drawable.button_clear);
            cleanButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.o5)));

            Button ceButton = findViewById(R.id.CE);
            ceButton.setBackgroundResource(R.drawable.button_clear);
            ceButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.o5)));

            // 切换彩蛋按钮图片
            eggshellView.setImageResource(R.drawable.logo);
        }
        count = !count;
    }
}